<template>
	<view class="calendar">
		<view class="header">
			<button @click="prevMonth">上一月</button>
			<text>{{ currentYear }}年{{ currentMonth }}月</text>
			<button @click="nextMonth">下一月</button>
		</view>
		<view class="days">
			<view v-for="(day, index) in days" :key="index" class="day" :class="{ punched: isPunched(day) }">
				{{ day }}
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: "Calender",
	props: {
		punchedDates: {
			type: Array,
			default: () => []
		}
	},
	data() {
		const now = new Date();
		return {
			currentYear: now.getFullYear(),
			currentMonth: now.getMonth() + 1,
			days: [] // 当前月份的所有天数
		};
	},
	methods: {
		generateDays() {
			const daysInMonth = new Date(this.currentYear, this.currentMonth, 0).getDate();
			this.days = Array.from({ length: daysInMonth }, (_, i) => i + 1);
		},
		isPunched(day) {
			// console.log("punchedDates is: ", this.punchedDates);
			const formattedDate = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			// 遍历 punchedDates 对象，检查是否存在对应的日期
			for (const key in this.punchedDates) {
				if (this.punchedDates[key].startsWith(formattedDate)) {
					return true;
				}
			}
			return false;
		},
		prevMonth() {
			if (this.currentMonth === 1) {
				this.currentYear -= 1;
				this.currentMonth = 12;
			} else {
				this.currentMonth -= 1;
			}
			this.generateDays();
		},
		nextMonth() {
			if (this.currentMonth === 12) {
				this.currentYear += 1;
				this.currentMonth = 1;
			} else {
				this.currentMonth += 1;
			}
			this.generateDays();
		}
	},
	mounted() {
		this.generateDays();
	}
};
</script>

<style scoped>
.calendar {
	padding: 20rpx;
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}
.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}
.header button {
	padding: 10rpx;
	background-color: #4caf50;
	color: white;
	border: none;
	border-radius: 8rpx;
	cursor: pointer;
}
.days {
	display: grid;
	grid-template-columns: repeat(7, 1fr);
	gap: 10rpx;
}
.day {
	text-align: center;
	padding: 10rpx;
	border-radius: 8rpx;
	background-color: #f5f5f5;
}
.day.punched {
	background-color: #4caf50;
	color: #fff;
}
</style>